<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Token;
use app\common\model\User;
use fast\Random;
use think\Db;
use think\Exception;
use think\Hook;

/**
 * 首页接口 123 4
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function getbanner(){


        $this->success("注册失败,请重试!",[]);
    }

    public function setting(){
        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx06b2a559d1df9a9c&redirect_uri=http://gzh.stp1.cn&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect

        $this->success("注册失败,请重试!",['appid'=>'wx06b2a559d1df9a9c']);
    }

    public function login(){

        $appid = 'wx06b2a559d1df9a9c'; //公众号信息
        $secret ='3232307ce5f27b99beec2b81b4468f95';//公众号信息

        $code = $this->request->param('code');



        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";


        $ret = file_get_contents($url);
        $ret = json_decode($ret, 'true');



        $access_token = $ret['access_token'];
        $openid = $ret['openid'];


        $urlb = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";


        $rets = file_get_contents($urlb);

        $rets = json_decode($rets, 'true');





        $uid='';
        if (isset($rets['openid'])) {
            $openid = $rets['openid'];

            $get = Db::name('user')->where(['openid'=>$openid])->find();

            $account='';

            if ($get) {

                $data['nickname'] = $rets['nickname'];
                $data['avatar'] = $rets['headimgurl'];
                $data['unionid'] = $rets['unionid'];


                Db::name('user')->where(['openid'=>$openid])->update($data);

            } else {

                $data['salt']='hahahaha';
                $data['unionid']=$rets['unionid'];

                $data['password']=md5(md5('111111') . 'hahahaha');
                $data['status']='normal';
                $data['username']=$openid;
                $data['nickname'] = $rets['nickname'];
                $data['avatar'] = $rets['headimgurl'];
                $data['openid'] = $openid;
                $data['createtime'] = time();

                Db::name('user')->insertGetId($data);

            }



            $this->auth->login($openid, '111111');

            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);

            die;
        } else {


            $this->error("注册失败,请重试!");
        }
    }




}
